# -*- coding: utf-8 -*-

import json
import logging
from datetime import datetime
from odoo import http, fields
from odoo.http import request
from odoo.exceptions import ValidationError, AccessError
from .api_base import api_response, verify_api_token, check_department_permission
import io

_logger = logging.getLogger(__name__)


class CategoryController(http.Controller):
    """设备类别管理控制器"""

    @http.route('/api/category/list', type='json', auth='none', methods=['POST'], csrf=False, cors='*')
    # #@api_response
    @verify_api_token
    # @check_api_permission('device:category:list')  # 已注释按钮权限，改用部门权限
    @check_department_permission
    def list_category(self, **kwargs):
        """获取设备类别列表"""
        page = kwargs.get('pageNum', 1)
        size = kwargs.get('pageSize', 10)
        name = kwargs.get('name', '')
        code = kwargs.get('code', '')
        status = kwargs.get('status', '')
        parent_id = kwargs.get('parentId', '')

        domain = []
        if name:
            domain.append(('name', 'ilike', name))
        if code:
            domain.append(('code', 'ilike', code))
        if status is not None and status != '':
            domain.append(('status', '=', bool(int(status))))
        if parent_id:
            domain.append(('parent_id', '=', int(parent_id)))

        # 计算总数
        total = request.env['device.category'].sudo().search_count(domain)

        # 获取数据
        offset = (page - 1) * size
        categories = request.env['device.category'].sudo().search(domain, offset=offset, limit=size)

        # 构建返回数据
        rows = []
        for category in categories:
            rows.append({
                'categoryId': category.id,
                'name': category.name,
                'completeName': category.complete_name,
                'code': category.code,
                'description': category.description or '',
                'parentId': category.parent_id.id if category.parent_id else None,
                'parentName': category.parent_id.name if category.parent_id else '',
                'sequence': category.sequence,
                'status': category.status,
                'deviceCount': category.device_count,
                'createTime': category.create_time.strftime('%Y-%m-%d %H:%M:%S') if category.create_time else '',
                'remark': category.remark or '',
                'hasChildren': len(category.child_ids) > 0
            })
        return {
            'code': 200,
            'msg': '查询成功',
            'data': {
                'total': total,
                'rows': rows
            }
        }

    @http.route('/api/category/tree', type='json', auth='none', methods=['POST'], csrf=False, cors='*')
    # @api_response
    @verify_api_token
    # @check_api_permission('device:category:list')  # 已注释按钮权限，改用部门权限
    @check_department_permission
    def get_category_tree(self, **kwargs):
        """获取设备类别树"""
        _logger.info("=== 开始获取设备类别树 ===")

        # 获取当前用户
        current_user = getattr(request, 'current_api_user', None)
        _logger.info(f"当前用户: {current_user.login if current_user else 'None'}")

        # 检查是否为admin用户或超级管理员
        is_admin = False
        if current_user:
            # 检查device.user中的admin标记
            device_user = request.env['device.user'].sudo().search([
                ('username', '=', current_user.login)
            ], limit=1)
            if device_user and device_user.is_admin:
                is_admin = True
                _logger.info(f"用户 {current_user.login} 是超级管理员")
            else:
                _logger.info(f"用户 {current_user.login} 不是超级管理员")

        # 先查询所有类别（调试用）
        all_categories = request.env['device.category'].sudo().search([])
        _logger.info(f"数据库中总共有 {len(all_categories)} 个设备类别")

        # 如果是admin，获取所有类别，否则只获取状态为True的类别
        if is_admin:
            categories = all_categories
            _logger.info(f"admin用户，返回所有 {len(categories)} 个类别")
        else:
            categories = request.env['device.category'].sudo().search([('status', '=', True)])
            _logger.info(f"普通用户，返回状态为True的 {len(categories)} 个类别")

        def build_tree(parent_id=None):
            tree = []
            _logger.info(f"构建树结构，parent_id: {parent_id}")

            # 修正过滤逻辑
            if parent_id is None:
                # 查找顶级节点（parent_id为False或None的记录）
                filtered_categories = categories.filtered(lambda c: not c.parent_id)
            else:
                # 查找指定父节点的子节点
                filtered_categories = categories.filtered(lambda c: c.parent_id and c.parent_id.id == parent_id)

            _logger.info(f"找到 {len(filtered_categories)} 个匹配的类别")

            for category in filtered_categories:
                _logger.info(
                    f"处理类别: ID={category.id}, 名称={category.name}, 父ID={category.parent_id.id if category.parent_id else None}")
                children = build_tree(category.id)
                tree.append({
                    'id': category.id,
                    'label': category.name,
                    'value': category.id,
                    'code': category.code,
                    'children': children if children else None
                })
            return tree

        tree_data = build_tree()
        _logger.info(f"最终树结构: {tree_data}")

        return {
            'code': 200,
            'msg': '查询成功',
            'data': tree_data
        }

    @http.route('/api/category/info/<int:category_id>', type='json', auth='none', methods=['POST'], csrf=False,
                cors='*')
    # @api_response
    @verify_api_token
    # @check_api_permission('device:category:read')  # 已注释按钮权限，改用部门权限
    @check_department_permission
    def get_category(self, category_id, **kwargs):
        """获取设备类别详情"""
        category = request.env['device.category'].sudo().browse(category_id)
        if not category.exists():
            raise ValidationError('设备类别不存在')

        data = {
            'categoryId': category.id,
            'name': category.name,
            'completeName': category.complete_name,
            'code': category.code,
            'description': category.description or '',
            'parentId': category.parent_id.id if category.parent_id else None,
            'parentName': category.parent_id.name if category.parent_id else '',
            'sequence': category.sequence,
            'status': category.status,
            'deviceCount': category.device_count,
            'createTime': category.create_time.strftime('%Y-%m-%d %H:%M:%S') if category.create_time else '',
            'updateTime': category.update_time.strftime('%Y-%m-%d %H:%M:%S') if category.update_time else '',
            'createBy': category.create_by,
            'updateBy': category.update_by,
            'remark': category.remark or ''
        }

        return {
            'code': 200,
            'msg': '查询成功',
            'data': data
        }

    @http.route('/api/category/add', type='json', auth='none', methods=['POST'], csrf=False, cors='*')
    # @api_response
    @verify_api_token
    # @check_api_permission('device:category:add')  # 已注释按钮权限，改用部门权限
    @check_department_permission
    def add_category(self, **kwargs):
        """新增设备类别"""
        name = kwargs.get('name')
        code = kwargs.get('code')
        description = kwargs.get('description', '')
        parent_id = kwargs.get('parentId')
        sequence = kwargs.get('sequence', 10)
        status = kwargs.get('status', True)
        remark = kwargs.get('remark', '')

        if not name or not code:
            raise ValidationError('类别名称、类别编码为必填项')

        vals = {
            'name': name,
            'code': code,
            'description': description,
            'sequence': int(sequence),
            'status': bool(status),
            'remark': remark
        }

        if parent_id:
            vals['parent_id'] = int(parent_id)

        category = request.env['device.category'].sudo().create(vals)

        return {
            'code': 200,
            'msg': '成功',
            'data':{'categoryId': category.id}
        }

    @http.route('/api/category/edit', type='json', auth='none', methods=['POST'], csrf=False, cors='*')
    # @api_response
    @verify_api_token
    # @check_api_permission('device:category:edit')  # 已注释按钮权限，改用部门权限
    @check_department_permission
    def edit_category(self, **kwargs):
        """修改设备类别"""
        category_id = kwargs.get('categoryId')
        if not category_id:
            raise ValidationError('类别ID不能为空')

        category = request.env['device.category'].sudo().browse(int(category_id))
        if not category.exists():
            raise ValidationError('设备类别不存在')

        vals = {}
        if 'name' in kwargs:
            vals['name'] = kwargs['name']
        if 'code' in kwargs:
            vals['code'] = kwargs['code']
        if 'description' in kwargs:
            vals['description'] = kwargs['description']
        if 'parentId' in kwargs:
            vals['parent_id'] = int(kwargs['parentId']) if kwargs['parentId'] else False
        if 'sequence' in kwargs:
            vals['sequence'] = int(kwargs['sequence'])
        if 'status' in kwargs:
            vals['status'] = bool(kwargs['status'])
        if 'remark' in kwargs:
            vals['remark'] = kwargs['remark']

        category.write(vals)

        return {
            'code': 200,
            'msg': '',
        }

    @http.route('/api/category/delete', type='json', auth='none', methods=['POST'], csrf=False, cors='*')
    # @api_response
    @verify_api_token
    # @check_api_permission('device:category:delete')  # 已注释按钮权限，改用部门权限
    @check_department_permission
    def delete_category(self, **kwargs):
        """删除设备类别"""
        category_ids = kwargs.get('categoryIds', [])
        if not category_ids:
            raise ValidationError('请选择要删除的设备类别')

        categories = request.env['device.category'].sudo().browse(category_ids)
        categories.unlink()

        return {
            'code': 200,
            'msg': '',
        }

    @http.route('/api/category/export', type='http', auth='none', methods=['GET'], csrf=False, cors='*')
    @verify_api_token
    # @check_api_permission('device:category:export')  # 已注释按钮权限，改用部门权限
    @check_department_permission
    def export_category(self, **kwargs):
        """导出设备类别信息"""
        # 获取查询条件
        name = kwargs.get('name', '')
        code = kwargs.get('code', '')
        status = kwargs.get('status', '')
        parent_id = kwargs.get('parentId', '')

        domain = []
        if name:
            domain.append(('name', 'ilike', name))
        if code:
            domain.append(('code', 'ilike', code))
        if status is not None and status != '':
            domain.append(('status', '=', bool(int(status))))
        if parent_id:
            domain.append(('parent_id', '=', int(parent_id)))

        categories = request.env['device.category'].sudo().search(domain)

        # 构建Excel数据
        import xlsxwriter
        output = io.BytesIO()
        workbook = xlsxwriter.Workbook(output)
        worksheet = workbook.add_worksheet('设备类别信息')

        # 设置标题
        headers = [
            '类别编码', '类别名称', '完整名称', '类别描述', '上级类别',
            '排序', '状态', '设备数量', '创建时间', '备注'
        ]

        # 写入标题
        for col, header in enumerate(headers):
            worksheet.write(0, col, header)

        # 写入数据
        for row, category in enumerate(categories, 1):
            data = [
                category.code,
                category.name,
                category.complete_name,
                category.description or '',
                category.parent_id.name if category.parent_id else '',
                category.sequence,
                '启用' if category.status else '停用',
                category.device_count,
                category.create_time.strftime('%Y-%m-%d %H:%M:%S') if category.create_time else '',
                category.remark or ''
            ]

            for col, value in enumerate(data):
                worksheet.write(row, col, value)

        workbook.close()
        output.seek(0)

        # 生成文件名
        filename = f"设备类别信息_{datetime.now().strftime('%Y%m%d_%H%M%S')}.xlsx"

        response = request.make_response(
            output.getvalue(),
            headers=[
                ('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'),
                ('Content-Disposition', f'attachment; filename="{filename}"')
            ]
        )
        output.close()
        return response
